package com.lain.wx.controller;

import com.lain.wx.utils.CheckUtil;
import com.lain.wx.utils.MessageType;
import com.lain.wx.utils.MessageUtil;
import com.lain.wx.vo.ReplyMsg;
import com.lain.wx.vo.UserMsg;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Title:       WxCliController Description: 7thmist微公号后台
 *
 * @author : liugaoyang date         : 2019/11/13 16:59
 */
@RestController
@RequestMapping("/api")
public class WxCliController {

    @GetMapping("/test")
    public String test() {
        return "hello ";
    }

    /**
     * 验证消息是否来自微信服务器
     * @param req
     * @return
     */
    @GetMapping("/wx")
    public String wx(HttpServletRequest req) {
        String signature = req.getParameter("signature");
        String timestamp = req.getParameter("timestamp");
        String nonce = req.getParameter("nonce");
        String echostr = req.getParameter("echostr");

        if (CheckUtil.checkSignature(signature, timestamp, nonce)) {
            return echostr;
        } else {
            return "";
        }
    }

    /**
     * 你问我答
     * @param request
     * @return
     */
    @PostMapping("/wx")
    public String replyMessage(HttpServletRequest request) {
        Map<String, String> map = MessageUtil.xmlToMap(request);
        String toUserName = map.get("ToUserName");
        String fromUserName = map.get("FromUserName");
        String msgType = map.get("MsgType");
        String content = map.get("Content");
        String message = "success";
        if (MessageType.REQ_MESSAGE_TYPE_TEXT.equals(msgType)) {
            // 回复文本信息触发的消息
            if(content != null && content.trim().toLowerCase().equals(UserMsg.VMWARE)) {
                message = MessageUtil.initText(toUserName, fromUserName, MessageType.REQ_MESSAGE_TYPE_TEXT, ReplyMsg.VM_BAIDU_PAN);
            }
            if(content != null && content.trim().toLowerCase().equals(UserMsg.JRE)) {
                message = MessageUtil.initText(toUserName, fromUserName, MessageType.REQ_MESSAGE_TYPE_TEXT, ReplyMsg.JRE_BAIDU_PAN);
            }
            if(content != null && content.trim().toLowerCase().equals(UserMsg.QHDFL)) {
                message = MessageUtil.initText(toUserName, fromUserName, MessageType.REQ_MESSAGE_TYPE_TEXT, ReplyMsg.QHDFL_BAIDU_PAN);
            }
        } else if (MessageType.REQ_MESSAGE_TYPE_EVENT.equals(msgType)) {
            // 关注时触发的消息
            String event = map.get("Event");
            if (MessageType.EVENT_TYPE_SUBSCRIBE.equals(event)) {
                message = MessageUtil.initText(toUserName, fromUserName, MessageType.REQ_MESSAGE_TYPE_TEXT, ReplyMsg.NEW_MEMBER_SAY_HELLO);
            }
        }
        return message;
    }


}